package com.jxb.lession76.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MapperUtil {
    private static SqlSessionFactory factory;
    private static final ThreadLocal<SqlSession> SESSION = new ThreadLocal<>();

    static{
        try {
            InputStream is = Resources.getResourceAsStream("mybatis_config.xml");
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static <T> T getMapper(Class<T> clazz){
        SqlSession session = getSession();
        return session.getMapper(clazz);
    }

    public static SqlSession getSession(){
        SqlSession session = SESSION.get();
        if (session == null) {
            session = factory.openSession();
            SESSION.set(session);
        }
        return session;
    }

    public static void close(SqlSession session){
        try {
            session.close();
        } finally {
            SESSION.remove();
        }
    }

    public static void commit(){
        SqlSession session = getSession();
        session.commit();
        close(session);
    }

    public static void rollback(){
        SqlSession session = getSession();
        session.rollback();
        close(session);
    }

}
